package steed.ext.filter;

import java.io.IOException;

import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import steed.domain.BaseUser;
import steed.domain.application.DWZMessage;
import steed.domain.system.AdminUser;
import steed.ext.domain.user.User;
import steed.filter.BaseAdminFilter;
import steed.hibernatemaster.util.DaoUtil;
import steed.util.base.BaseUtil;
import steed.util.base.PropertyUtil;
import steed.util.base.StringUtil;
import steed.util.digest.AESUtil;
import steed.util.http.HttpUtil;
import steed.util.system.LoginUtil;

//@WebFilter(urlPatterns={"/admin/*","/hadmin/*"},filterName="m")
public class AdminFilter extends BaseAdminFilter{

	@Override
	protected BaseUser login(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		DWZMessage dwzMessage = new DWZMessage();
		if (LoginUtil.isLoginCountOverproof(request.getRemoteAddr())) {
			dwzMessage.setTitle("登录错误次数过多");
			dwzMessage.setMessage("您短时间内登录错误次数过多，请稍后再试。");
			dwzMessage.setStatusCode(DWZMessage.statusCode_fail);
		}else{
			AdminUser people = null;
			try {
				people = DaoUtil.get((Class<AdminUser>) Class.forName(PropertyUtil.getConfig("adminUserClass")), request.getParameter("nickName"));
			} catch (ClassNotFoundException e) {
				if (StringUtil.isStringEmpty(PropertyUtil.getConfig("userClass"))) {
					BaseUtil.getLogger().error("请到config.properties中配置adminUserClass类!", e);
				}else {
					BaseUtil.getLogger().error("未找到config.properties中配置的adminUserClass类!", e);
				}
			}
			if (people == null) {
				dwzMessage.setTitle("登录失败");
				dwzMessage.setMessage("用户不存在!");
				dwzMessage.setStatusCode(DWZMessage.statusCode_fail);
			}/*else if(people.getUserType() != 0){
				dwzMessage.setTitle("登录失败");
				dwzMessage.setMessage("您的用户类型不能登录该后台!");
				dwzMessage.setStatusCode(DWZMessage.statusCode_fail);
			}*/else if(!people.getPassword().equals(AESUtil.aesEncode(request.getParameter("password")))){
				dwzMessage.setTitle("登录失败");
				dwzMessage.setMessage("用户名或密码错误");
				dwzMessage.setStatusCode(DWZMessage.statusCode_fail);
				LoginUtil.makeLoginLog(request.getRemoteAddr(), request.getParameter("nickName"), dwzMessage.getMessage(), 3);
			}else {
				dwzMessage.setMessageAndTitle("登录成功");
				dwzMessage.setStatusCode(DWZMessage.statusCode_success);
				LoginUtil.makeLoginLog(request.getRemoteAddr(), request.getParameter("nickName"), dwzMessage.getMessage(), 0);
				HttpUtil.writeJson(response, dwzMessage);
				return people;
			}
		}
//		Message message = new LoginUtil().login(request);
		HttpUtil.writeJson(response, dwzMessage);
		return null;
	}
}
